package com.wish.g01.contract.sign;


import java.io.FileInputStream;

import java.security.GeneralSecurityException;

import java.io.IOException;

import com.itextpdf.io.codec.Base64;
import com.itextpdf.kernel.geom.Rectangle;

import org.bouncycastle.util.io.Streams;

import org.springframework.stereotype.Service;



@Service
public class MarkService {

    public void markPdf() {
        DeferredSignPdfAssLry signPdfAss = new DeferredSignPdfAssLry();
        Rectangle rectangle = new Rectangle(36, 448, 200, 100);
        SignInfo signInfo = new SignInfo(rectangle,1,"第一次签名","维数公寓","SIGNATURE_A",DeferredSignPdfAssLryTest.singImg,true);
        //获取空的签名文件
        ExternalEmptySignatureContainer externalSignatureContainer = new ExternalEmptySignatureContainer(signPdfAss.getDicFilter(),signPdfAss.getDicSubfilter(),signPdfAss.getHashAlgorithm());
        //初始化
        try {
            signPdfAss.initSigner(Streams.readAll(new FileInputStream(DeferredSignPdfAssLryTest.SOURCEFILE)),DeferredSignPdfAssLryTest.TEMPFILE,signInfo,externalSignatureContainer);
        } catch (IOException | GeneralSecurityException e) {
            System.out.println("初始化签名对象异常");
            e.printStackTrace();
        }
        //待签名哈希,发给外部服务器进行签名
        String ToSignHash = Base64.encodeBytes(externalSignatureContainer.getDigestHash()) ;
        String signedHash = null;//cfca签名后的哈希值
        try {
            signedHash = SignService.sign(ToSignHash,signPdfAss.getHashAlgorithm());
        } catch (GeneralSecurityException e) {
            System.out.println("签名异常！");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("签名异常！");
            e.printStackTrace();
        }
        //验签，这一步需要通过外部服务器返回的signedHash，与原文件哈希值externalSignatureContainer.getDigestHash()进行验证
        byte[] cmsInfo = Base64.decode(signedHash);
        try {
            DeferredSignPdfAssLry.embedSignature(DeferredSignPdfAssLryTest.TEMPFILE,DeferredSignPdfAssLryTest.RESULTFILE,"SIGNATURE_A",new EmbdedSignatureContainer(cmsInfo));
        } catch (IOException e) {
            System.out.println("分离签名异常！");
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            System.out.println("分离签名异常！");
            e.printStackTrace();
        }
    }

}
